package com.lql.lqlreader.util

import android.annotation.SuppressLint
import android.os.Build
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.view.WindowManager
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.ActionBar
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import com.lql.lqlreader.R

/**
 * ClassName: ToolbarHelper
 * Description: extract public methods from original and center
 * Date: 2021/06/17
 */

class ToolbarHelper {

    companion object {
        @SuppressLint("StaticFieldLeak")
        private lateinit var toolbarTitle: TextView

        // 此方法未用过
        fun checkSdkVersionToTranslucentFlag(window: Window) {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
                val attributes = window.attributes
                attributes.flags = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
            }
        }

        fun initToolbar(activity: AppCompatActivity) {
            val toolbar = activity.findViewById<Toolbar>(R.id.toolbar)
            if (toolbar != null) {
                activity.setSupportActionBar(toolbar)
                toolbarTitle = toolbar.findViewById(R.id.toolbarTitle)
            }
        }

        // 此方法和下面的方法都是创建新的view
        fun setContentView(activity: AppCompatActivity, layoutResID: Int) {
            activity.setContentView(View.inflate(activity, layoutResID, null))
        }

        fun setContentView(activity: AppCompatActivity, view: View) {
            val rootLayout: LinearLayout = activity.findViewById(R.id.rootLayout)
            if (rootLayout == null) return
            rootLayout.addView(view, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
            initToolbar(activity)
        }

        fun hideHomeAsUp(actionBar: ActionBar) {
            actionBar.setDisplayHomeAsUpEnabled(false)
        }

        fun showHomeAsUp(actionBar: ActionBar) {
            actionBar.setDisplayHomeAsUpEnabled(true)
        }

        fun setLeftTitle(actionBar: ActionBar, title: String) {
            actionBar.title = ""

            if (toolbarTitle != null) {
                toolbarTitle.text = HtmlUtils.translation(title)
                toolbarTitle.ellipsize = TextUtils.TruncateAt.MARQUEE // 如果内容过长会有跑马灯效果
                toolbarTitle.isSingleLine = true // 单行设置
                toolbarTitle.isSelected = true // 可选设置
                toolbarTitle.isFocusable = true // 可聚焦设置，即鼠标可以选中
                toolbarTitle.isFocusableInTouchMode = true // 同上，此时用户可复制文本
            }
        }
    }

}
